﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using SQLiteCoreDB;
using SQLiteCoreDB.Common;
using SQLiteCoreDB.Context;
using SQLiteCoreDB.Models;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Xml.Linq;
using WebFile.Models;
namespace WebFile.Controllers
{
    /// <summary>
    /// 登录，处理
    /// </summary>
    [AllowAnonymous]
    public class LoginHandleController : Controller
    {
        private readonly static List<Claim> _administrator = new List<Claim>() {
             new Claim(ClaimTypes.Role,"admin"),
             new Claim(ClaimTypes.Role,"user"),
        };
        private ChartApp _db = SL.db;
        /// <summary>
        /// 普通用户权限配置
        /// </summary>
        private readonly static List<Claim> _user = new List<Claim>() {
             new Claim(ClaimTypes.Role,"user"),
        };
        //视图，登录
        public ActionResult LoginView()
        {


            return View();
        }

        //退出登录
        public ActionResult ExitLogin()
        {
            Response.Cookies.Delete(KeyValueConfig.Cookie_Token);
            return Redirect("/Home/Index");
        }

        public ActionResult CeShi()
        {
            Console.WriteLine("——————————你哈怂——————");
            return Json(new Result("账号不可为空"));
        }
        //处理登录，
        public ActionResult DoLogin(string account, string pwd)
        {
            if (string.IsNullOrWhiteSpace(account))
            {
                return Json(new Result("账号不可为空"));
            }
            if (string.IsNullOrWhiteSpace(pwd))
            {
                return Json(new Result("密码不可为空"));
            }

            var users = _db.Login.Where(d => d.username == account);
            if (users != null && users.Count() > 0)
            {
                var One = users.FirstOrDefault();
                string storedPassword = One?.password;
                if (pwd.Trim().Equals(storedPassword))
                {

                    string role = One.role;
                    bool ce = role.Equals("admin");
                    role = One.LV.ToString();


                    var credentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(KeyValueConfig.TokeKey)), SecurityAlgorithms.HmacSha256);
                    var claims = new List<Claim>();

                    claims = ce ? _administrator : _user;//管理权限

                    claims.Add(new Claim(ClaimTypes.Name, account));
                    claims.Add(new Claim(ClaimTypes.Name, role));

                    var token = new JwtSecurityToken(
                        issuer: KeyValueConfig.issuer,
                        audience: KeyValueConfig.audience,
                        claims: claims,
                        expires: DateTime.UtcNow.AddDays(7),
                        signingCredentials: credentials
                    );
                    var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
  
                    var userToken = new CookieOptions
                    {
                        Expires = DateTime.Now.AddDays(7),
                        HttpOnly = true,
                        IsEssential = true,
                        SameSite = SameSiteMode.Strict
                    };
                 
                    Response.Cookies.Append(KeyValueConfig.Cookie_Token, jwtToken, userToken);


                    return Json(new Result(jwtToken, 1));
                }
                else
                {
                    return Json(new Result("密码错误"));
                }
            }
            // 创建JWT

            return Json(new Result("未知用户"));

        }
        [HttpPost("/LoginHandle/DoRegister/{account}/{pwd}")]
        public ActionResult DoRegister(string account, string pwd)
        {
            if (string.IsNullOrWhiteSpace(account))
            {
                return Json(new Result("账号不可为空"));
            }
            if (string.IsNullOrWhiteSpace(pwd))
            {
                return Json(new Result("密码不可为空"));
            }
            if (account.Length >= 6 || pwd.Length >= 6)
            {
                return Json(new Result("长度请勿大于6位"));
            }

            var users = _db.Login.Where(d => d.username == account);


            if (users.Count() > 0)
            {
                return Json(new Result("账号已存在"));
            }

            Login Newlogin = new Login()
            {
                username = account,
                password = pwd,
                role = "user",
                LV = 1
            };

            _db.Login.Add(Newlogin);
            _db.SaveChanges();
            return Json(new Result("注册成功", 1));
        }

 
        public ActionResult P403()
        {
            return View();
        }
    }
}